<template>
  <div>
    <EditorVue
        :content="content"
        :readOnlys="readOnlys"
        @changeData="hChangeData"
        @uploadImg="hUploadImg"
    />
    <el-divider></el-divider>

    <!--      <el-row :gutter="24">-->
    <!--        <el-col :span="12">-->
    <!--          <div class="addText" style="float:right">-->
    <!--            <el-button type="success" class="butT" @click="dialogFormVisible1 = true" >发布文档</el-button>-->
    <!--          </div>-->
    <!--        </el-col>-->
    <!--        <el-col :span="11">-->
    <!--          <div class="addFromLocal" style="float:right">-->
    <!--            <el-button type="primary" class="butT" @click="dialogFormVisible2 = true" >选择本地文件</el-button>-->
    <!--          </div>-->
    <!--        </el-col>-->
    <!--      </el-row>-->


    <!-- 文档信息编辑 -->
    <div>
      <!--        <el-dialog title="文档信息" :visible.sync="dialogFormVisible1">-->
      <div class="form">
        <el-form :model="ruleForm" ref="ruleForm" label-width="100px" class="demo-ruleForm" :rules="formRule">
          <el-form-item label="文档分类" prop="module">
            <el-select v-model="ruleForm.module" placeholder="请选择文档类别" style="float: left">
              <el-option label="节气" value="节气"></el-option>
              <el-option label="环境" value="环境"></el-option>
              <el-option label="旅游" value="旅游"></el-option>
              <el-option label="生态" value="生态"></el-option>
              <el-option label="气象科普" value="气象科普"></el-option>
            </el-select>
          </el-form-item>

          <!--            <el-form-item label="是否为通知" prop="notice" style="text-align:left;float:left;padding-right: 60px;margin-left: 10px">-->
          <!--                <el-checkbox label="" name="notice" v-model="ruleForm.notice"></el-checkbox>-->
          <!--            </el-form-item>-->


          <el-form-item label="文档标题" prop="nTitle">
            <el-input v-model="ruleForm.title" style="width: 220px;float: left"></el-input>
          </el-form-item>


<!--          <el-form-item label="作者" prop="nAuthor">-->
<!--            <el-input v-model="ruleForm.nAuthor" style="width: 220px;float: left"></el-input>-->
<!--          </el-form-item>-->

          <div v-if="this.ruleForm.isMain===1 && isdeleteImg === false">
            <el-form-item label="首页图片" prop="pIc" style="text-align: left;" v-if="ruleForm.pic.length!== 0 && isdeleteImg===false">
              <el-image
                  style="width: 100px; height: 100px ; margin-left: 25px"
                  :src="url"
                  fit="scale-down">
              </el-image>
              <el-button @click="deleteImg" type="danger" size="mini" style="float: right;margin: 35px 60px 0px 0px">删除图片</el-button>
            </el-form-item>

          </div>
          <el-form-item label="设为首页新闻" prop="nNews" style="text-align: left;padding-left: 120px" v-if="ruleForm.isMain === 0">
              <el-checkbox label="" name="news" v-model="isNews" :checked="isNews"></el-checkbox>
            </el-form-item>

          <div class="img" v-if="isNews===true">
            <el-upload
                class="upload-demo"
                drag
                ref="upload"
                accept=".jpg,.png,.jpeg,.bmp,.webp"
                action="string"
                :multiple="false"
                :limit="1"
                :http-request="uploadFileAndParams"
                :auto-upload="false"
                :on-remove="handleRemove"
                :before-upload="beforeAvatarUpload"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip"><strong>jpg/png/jpeg/bmp/webp</strong>，且<strong>不超过2MB</strong>
                <br/>
                为达到最好效果，请选择<strong>长1000高200</strong>的图片</div>
            </el-upload>
          </div>

          <el-form-item style="padding:0px 80px 10px 0px;">
            <el-button type="primary" @click="submitForm()">提交</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>

        </el-form>
      </div>
      <!--      </el-dialog>-->
    </div>

    <!--    <div>-->
    <!--      &lt;!&ndash; 选择本地文件弹窗 &ndash;&gt;-->
    <!--      <el-dialog title="选择本地文档" :visible.sync="dialogFormVisible2">-->
    <!--        <el-upload-->
    <!--          class="upload-demo"-->
    <!--          ref="upload"-->
    <!--          action="https://jsonplaceholder.typicode.com/posts/"-->
    <!--          accept=".xlsx,.xls"-->
    <!--          :limit="1"-->
    <!--          :on-preview="handlePreview"-->
    <!--          :on-remove="handleRemove"-->
    <!--          :file-list="fileList"-->
    <!--          :auto-upload="false">-->
    <!--          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>-->
    <!--          <el-button  style="margin-left: 10px;" size="small" type="success" plain @click="dialogFormVisible = true">编辑文档信息</el-button>-->
    <!--          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>-->
    <!--          <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件，且不超过500kb</div>-->
    <!--        </el-upload>-->
    <!--      <ChooseLocalFile/>-->


    <!--      </el-dialog>-->
    <!--    </div>-->

  </div>
</template>

<script>
import EditorVue from '../components/editorVue.vue'
// import ChooseLocalFile from "@/components/ChooseLocalFile";
export default {
  name: "UpdateNewsComponent",
  components: {
    EditorVue,
    // ChooseLocalFile
  },
  //从父组件传过来的数据，为回显的数据
  props: {
    from: {
      type: String,
      default: ''
    },
    oldRuleForm: {
      type: String, //数据类型有 String、Number、Boolean、Array ...
      default: ''// 默认值
    },
    dialogFormVisible0: {
      type: Boolean,
      default: true
    },

  },
  data() {
    // this.ruleForm=JSON.parse(this.formData);
    return {
      isdeleteImg:false,
      url: VUE_APP_URL.BASE_URL+ '/file/img/',
      isNews: false,
      params:new FormData(),
      readOnlys: false,
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      content: '',
      ruleForm: {
        nPic:''
      },
      rules: {
        title: [
          {required: true, message: '请输入文档名称', trigger: 'blur'},
          {min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur'}
        ],
        nAuthor: [
          {required: true, message: '请输入作者名称', trigger: 'blur'},
          {min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur'}
        ],
      },
      formRule: {
        title: [
          {required: true, message: '请输入标题名称', trigger: 'blur'},
          {min: 3, max: 200, message: '长度在 3 到 200 个字符', trigger: 'blur'}
        ],
        nClass:{
          required: true, trigger: 'blur',
        }
      },
      fileList: []
    };
  },
  methods: {
    uploadFileAndParams(param) {
      this.params.append("picture", param.file)
    },
    handleRemove(file, fileList) {
      this.params.remove('file');
    },
    hChangeData(editDataHtml) {
      // 获取最新的html数据
      this.content = editDataHtml
    },
    hUploadImg(file, insertFn) {
      // 插入图片，调接口返回图片url,通过插入conteng
      var params=new FormData();
      params.append("file",file)
     this.$axios({
        url:'/file/uploadFile2',
        method: 'POST',
        // transformRequest: [function(data, headers) {
        //   // 去除post请求默认的Content-Type
        //   delete headers.post['Content-Type']
        //   return data
        // }],
        data: params
      }).then((res) => {

        var jason = eval("(" + res.data + ")");
        insertFn(jason.data.url)
      })
      // let imgUrl = 'https://img1.baidu.com/it/u=608404415,1639465523&fm=253&fmt=auto&app=120&f=JPEG?w=1280&h=800'
      // insertFn(imgUrl);


      // 设置只读
      // this.readOnlys = true;
    },
    //限定添加新闻图片的图片大小
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    submitForm() {
      this.$refs["ruleForm"].validate((valid) => {
        let config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        };
        let params = new FormData();
        if (valid) {
          if (this.isNews === true) {
            // if(this.params.get("pic")===null){
            //   this.$message.error("请选择图片上传");
            //   return
            // }
            this.$refs.upload.submit();
            params.append('picture',this.params.get("pic"))
            this.params.append('isMain',1)

          }
          else{
            this.params.append('picture',null);
            params.append('picture',null)
            this.params.append('isMain',0)
          }
          // params.append("n_id", this.ruleForm.nId)
          // params.append("n_title", this.ruleForm.nTitle)
          // params.append("n_content", this.content)
          // params.append("n_class", this.ruleForm.nClass)
          // 先写死用来测试
          this.params.append("id", this.ruleForm.id)
          this.params.append("authorId", localStorage.getItem('authorId'))
          this.params.append("title", this.ruleForm.title)
          this.params.append("content", this.content)
          this.params.append("module", this.from)
          this.params.append("esId", this.ruleForm.esId)
          this.$axios.post("/article/article/modifyArticle/", this.params,config).then(
              (res) => {
                if (res.data.code === 200) {
                  this.$message.success("修改成功!");
                } else if (res.data.code === 401) {
                  this.$message.error("无权限！");
                } else {
                  this.$message.error("修改失败")
                }

              }
          ).finally(() => {
            this.shutdown();
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleChange(event) {
      console.log(event)
      // document.getElementById("img").style.display="block";
    },
    // 文件上传
    submitUpload() {
      this.$refs.upload.submit();
    },
    handlePreview(file) {
      console.log(file);
    },
    Img(param) {
      this.file = param.file;
    },
    uploadImg() {
      let fd = new FormData();
      fd.append('pic', this.file);
      fd.append('n_title', this.ruleForm.nTitle)
      fd.append('n_author', this.ruleForm.nAuthor)
      fd.append('n_class', this.ruleForm.nClass)
      fd.append('n_content', this.content)
      this.$axios.post('/news/addNews', fd).then((res) => {
        if (res.data.code === 200) {
          this.shutdown();
          this.$message.success("上传成功！")
        } else if (res.data.code === 401) {
          this.$message.error("无权限！");
        } else {
          this.$message.error('上传失败！')
        }
      }).finally(() => {
        this.shutdown();
      })
    },
    deleteImg() {
      this.isdeleteImg=true
      // this.$axios.post('/news/deletePic?n_id=' + this.ruleForm.nId).then((res) => {
      //   if (res.data.code === 200) {
      //     this.url = '';
      //     this.$message.success("删除成功！")
      //     this.isdeleteImg=true
      //     this.ruleForm.isMain=0
      //     this.isNews=false
      //   } else if (res.data.code === 401) {
      //     this.$message.error("无权限！");
      //   } else if (res.data.code === 500) {
      //     this.$message.success("服务器错误，请联系管理员！")
      //   } else {
      //     this.$message.error('删除失败！')
      //   }
      // }).finally(()=>{
      //   // this.$props.dialogFormVisible0 =false
      // })
    },
    shutdown: function () {
      this.$emit('update:shutdown', false)
    }
  },
  mounted() {
    this.ruleForm = JSON.parse(this.oldRuleForm);
    // console.log("=======================")
    // console.log(this.ruleForm)
    // console.log("=======================")

    // console.log("ruleform")
    // console.log(this.ruleForm)
    // let param = 'n_id=' + this.ruleForm.nId
    // this.$axios.get('/news/newsPic?' + param).then((res) => {
    //   if (res.data.code === 200) {
    //     this.isNews = true
    //     // res.data.data.
    //     let api = this.url;
    //     this.url = api + res.data.data
    //   } else if (res.data.code === 401) {
    //     this.$message.error("无权限！");
    //   }
    // })
    this.content = this.ruleForm.content;
    this.url=VUE_APP_URL.BASE_URL+'/article/article/download/'+this.ruleForm.pic+"?filePath=articles&fileName="+this.ruleForm.pic;
  }
};
</script>
<style scoped>
.form {
  width: 400px;
  margin: 0 auto;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
}

.img {
  padding-bottom: 10px;
}
</style>
